<?php
/**
 * 钉钉登录插件 - 保存配置
 */

header('Content-Type: application/json; charset=utf-8');

// 接收表单数据
$appKey = $_POST['app_key'] ?? '';
$appSecret = $_POST['app_secret'] ?? '';
$corpId = $_POST['corp_id'] ?? '';
$agentId = $_POST['agent_id'] ?? '';
$redirectUri = $_POST['redirect_uri'] ?? '';

// 验证必填项
if (empty($appKey) || empty($appSecret) || empty($corpId) || empty($redirectUri)) {
    echo json_encode([
        'success' => false,
        'message' => '请填写所有必填项'
    ]);
    exit;
}

// 验证 URL 格式
if (!filter_var($redirectUri, FILTER_VALIDATE_URL)) {
    echo json_encode([
        'success' => false,
        'message' => '回调地址格式不正确'
    ]);
    exit;
}

// 读取现有配置
$configFile = __DIR__ . '/../../config.php';
$config = [];
if (file_exists($configFile)) {
    $config = include $configFile;
}

// 更新钉钉配置
if (!isset($config['plugins'])) {
    $config['plugins'] = [];
}

if (!isset($config['plugins']['dingtalk'])) {
    $config['plugins']['dingtalk'] = [];
}

$config['plugins']['dingtalk']['app_key'] = $appKey;
$config['plugins']['dingtalk']['app_secret'] = $appSecret;
$config['plugins']['dingtalk']['corp_id'] = $corpId;
$config['plugins']['dingtalk']['agent_id'] = $agentId;
$config['plugins']['dingtalk']['redirect_uri'] = $redirectUri;

// 保存配置
$configContent = "<?php\n";
$configContent .= "/**\n";
$configContent .= " * 氚云API管理系统配置文件\n";
$configContent .= " * Alyr.net 企业级配置管理\n";
$configContent .= " */\n\n";
$configContent .= "return " . var_export($config, true) . ";\n";

if (file_put_contents($configFile, $configContent)) {
    echo json_encode([
        'success' => true,
        'message' => '钉钉配置保存成功'
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => '配置文件写入失败，请检查文件权限'
    ]);
}
